package cn.goodscript.web.servlet;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 所有ext与后台数据的请求都是由该Servlet来处理 前台必须传递一个mothed参数 该参数指定执行的方法名
 * 处理ext请求的这些方法格式都必须是:public String xxx(HttpServletRequest request)
 * 
 * @author 197370
 * 
 */
public class LoginServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 6039228711494931978L;

	/**
	 * 
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/json; charset=UTF-8");
		String mothed = request.getParameter("mothed");
		Object obj = null;
		// 根据参数mothed来判断执行的方法
		try {
			Method m = this.getClass().getMethod(mothed, HttpServletRequest.class);
			obj = m.invoke(this, request);
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		response.getWriter().write(obj.toString());
		response.flushBuffer();
	}

	public void login(HttpServletRequest request) {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
	}

	public String regist(HttpServletRequest request) {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String basefolder = "E:/chenwei/myProject/scriptDebug/web/userfile/" + username;
		File file = new File(basefolder);
		if (!file.exists()) {
			file.mkdirs();
		}
		StringBuffer sb = new StringBuffer();
		sb.append("{\'status\':\'succ\',");
		sb.append("\'basef\':\'");
		sb.append(basefolder + "\'}");
		return sb.toString();
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}
}
